package cn.iocoder.lw.module.core.controller.app.workorder;

import cn.iocoder.lw.framework.common.pojo.CommonResult;
import cn.iocoder.lw.framework.common.pojo.PageResult;
import cn.iocoder.lw.framework.common.util.object.BeanUtils;
import cn.iocoder.lw.module.core.controller.app.workorder.vo.workorder.*;
import cn.iocoder.lw.module.core.dal.dataobject.workorder.CoreWorkOrderDO;
import cn.iocoder.lw.module.core.enums.workorder.WorkOrderStatusEnum;
import cn.iocoder.lw.module.core.service.workorder.CoreWorkOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.iocoder.lw.framework.common.pojo.CommonResult.success;

@Tag(name = "用户 APP - 工单")
@RestController
@RequestMapping("/core/work-order")
@Validated
public class AppCoreWorkOrderController {

    @Resource
    private CoreWorkOrderService workOrderService;

    @PostMapping("/create")
    @Operation(summary = "创建工单")
    public CommonResult<Long> createWorkOrder(@Valid @RequestBody AppCoreWorkOrderCreateReqVO createReqVO) {
        return success(workOrderService.createWorkOrderApp(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新工单")
    public CommonResult<Boolean> updateWorkOrder(@Valid @RequestBody AppCoreWorkOrderUpdateReqVO updateReqVO) {
        workOrderService.updateWorkOrderApp(updateReqVO);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得工单")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<AppCoreWorkOrderRespVO> getWorkOrder(@RequestParam("id") Long id) {
        CoreWorkOrderDO workOrder = workOrderService.getWorkOrder(id);
        return success(BeanUtils.toBean(workOrder, AppCoreWorkOrderRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得工单分页")
    public CommonResult<PageResult<AppCoreWorkOrderRespVO>> getWorkOrderPage(@Valid AppCoreWorkOrderPageReqVO pageReqVO) {
        PageResult<CoreWorkOrderDO> pageResult = workOrderService.getWorkOrderPageApp(pageReqVO);
        return success(BeanUtils.toBean(pageResult, AppCoreWorkOrderRespVO.class));
    }

    @GetMapping("/my-initiated")
    @Operation(summary = "获得我发起的工单列表")
    public CommonResult<List<AppCoreWorkOrderRespVO>> getMyInitiatedWorkOrderList() {
        // TODO: 获取当前登录用户ID
        Long currentUserId = 1L; // 这里应该从SecurityContext获取
        List<CoreWorkOrderDO> list = workOrderService.getWorkOrderListByInitiatorId(currentUserId);
        return success(BeanUtils.toBean(list, AppCoreWorkOrderRespVO.class));
    }

    @GetMapping("/my-assigned")
    @Operation(summary = "获得我接单的工单列表")
    public CommonResult<List<AppCoreWorkOrderRespVO>> getMyAssignedWorkOrderList() {
        // TODO: 获取当前登录用户ID（member用户ID）
        Long currentUserId = 1L; // 这里应该从SecurityContext获取
        List<CoreWorkOrderDO> list = workOrderService.getWorkOrderListByAssigneeId(currentUserId);
        return success(BeanUtils.toBean(list, AppCoreWorkOrderRespVO.class));
    }

    @PostMapping("/accept")
    @Operation(summary = "接单")
    @Parameter(name = "id", description = "工单编号", required = true)
    public CommonResult<Boolean> acceptWorkOrder(@RequestParam("id") Long id) {
        // TODO: 获取当前登录用户ID（member用户ID）
        Long currentUserId = 1L; // 这里应该从SecurityContext获取
        workOrderService.acceptWorkOrder(id, currentUserId);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "更新工单状态")
    @Parameter(name = "id", description = "工单编号", required = true)
    @Parameter(name = "status", description = "新状态", required = true)
    public CommonResult<Boolean> updateWorkOrderStatus(@RequestParam("id") Long id,
                                                       @RequestParam("status") Integer status) {
        workOrderService.updateWorkOrderStatus(id, status);
        return success(true);
    }

    @PutMapping("/complete")
    @Operation(summary = "完成工单")
    public CommonResult<Boolean> completeWorkOrder(@Valid @RequestBody AppCoreWorkOrderUpdateReqVO updateReqVO) {
        // 完成工单时，需要检查当前用户是否是接单人
        CoreWorkOrderDO workOrder = workOrderService.getWorkOrder(updateReqVO.getId());
        if (workOrder == null) {
            return success(false);
        }

        // TODO: 获取当前登录用户ID（member用户ID）进行权限校验
        // Long currentUserId = getCurrentUserId();
        // if (!Objects.equals(workOrder.getAssigneeId(), currentUserId)) {
        //     throw exception(PERMISSION_DENIED);
        // }

        // 更新工单信息，包括完成状态、解决方案、费用等
        workOrderService.updateWorkOrderApp(updateReqVO);
        workOrderService.updateWorkOrderStatus(updateReqVO.getId(), WorkOrderStatusEnum.COMPLETED.getStatus());

        return success(true);
    }

    @GetMapping("/project/{projectId}")
    @Operation(summary = "根据项目编号获取工单列表")
    @Parameter(name = "projectId", description = "项目编号", required = true)
    public CommonResult<List<AppCoreWorkOrderRespVO>> getWorkOrderListByProjectId(@PathVariable("projectId") Long projectId) {
        List<CoreWorkOrderDO> list = workOrderService.getWorkOrderListByProjectId(projectId);
        return success(BeanUtils.toBean(list, AppCoreWorkOrderRespVO.class));
    }

    @GetMapping("/house/{houseId}")
    @Operation(summary = "根据房源编号获取工单列表")
    @Parameter(name = "houseId", description = "房源编号", required = true)
    public CommonResult<List<AppCoreWorkOrderRespVO>> getWorkOrderListByHouseId(@PathVariable("houseId") Long houseId) {
        List<CoreWorkOrderDO> list = workOrderService.getWorkOrderListByHouseId(houseId);
        return success(BeanUtils.toBean(list, AppCoreWorkOrderRespVO.class));
    }

    @GetMapping("/device/{deviceId}")
    @Operation(summary = "根据设备编号获取工单列表")
    @Parameter(name = "deviceId", description = "设备编号", required = true)
    public CommonResult<List<AppCoreWorkOrderRespVO>> getWorkOrderListByDeviceId(@PathVariable("deviceId") Long deviceId) {
        List<CoreWorkOrderDO> list = workOrderService.getWorkOrderListByDeviceId(deviceId);
        return success(BeanUtils.toBean(list, AppCoreWorkOrderRespVO.class));
    }

    // ==================== 工单状态枚举 ====================

    @GetMapping("/status-list")
    @Operation(summary = "获得工单状态列表")
    public CommonResult<List<WorkOrderStatusEnum>> getWorkOrderStatusList() {
        return success(List.of(WorkOrderStatusEnum.values()));
    }

}